package org.example;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageProducer;
import javax.jms.ObjectMessage;
import javax.jms.Session;
import javax.jms.Topic;
import java.util.Random;
import java.util.Scanner;
import java.util.Timer;
import java.util.TimerTask;

import org.apache.activemq.ActiveMQConnectionFactory;

public class Publisher {

    private static String brokerURL = "tcp://localhost:61616";
    private static ConnectionFactory factory;
    private Connection connection;
    private Session session;
    private MessageProducer producer;
    private Topic topic;
    private Random r = new Random();
    private int num = 0;

    public Publisher(String topicName) throws JMSException {

        factory = new ActiveMQConnectionFactory(brokerURL);
        connection = factory.createConnection();

        session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        topic = session.createTopic(topicName);
        producer = session.createProducer(topic);

        connection.start();
    }

    public void close() throws JMSException {
        if (connection != null) {
            connection.close();
        }
    }

    public static void main(String[] args) throws JMSException {
        Scanner scanner = new Scanner(System.in);
        Publisher publisher = new Publisher("MYTOPIC");
        // 产生10000个随机数字
        for(int i = 0; i < 10000; i++) {
            // 每隔10ms产生一个随机数字
            publisher.sendMessage();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        publisher.close();
    }

    public void sendMessage() throws JMSException {

        double signal = Math.sqrt(3.5)*r.nextGaussian() + 2.0;
        num++;
        System.out.println("第" + num + "个点：" + signal);
        Message message = session.createTextMessage("" + signal);
        producer.send(message);
    }

}
